package cn.com.elite;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.elite.algorithm.GUID;

public class Tongbu5314Thread implements Runnable{
	private static final Log log=LogFactory.getLog(Tongbu5314Thread.class);
	private boolean flag=true; //停止线程标记 
    private static int HZ=300;
    private static int num=500;
    private static int tongbu_num=500;
    private static int tongbu_num1=0;
    private static String xml="";
    private static String url="";
    private static String newguid="";
	public static String getUrl() {
		return url;
	}

	public static void setUrl(String url) {
		Tongbu5314Thread.url = url;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public int getHZ() {
		return HZ;
	}

	public void setHZ(int hz) {
		HZ = hz;
	}
	
	
	public static String getTxXml(String realtionID,DataSource dataSource1){
		String TxXml="";
		String APPL_NO_QA="";
		try{
			String DIST="";
			String BUSI_pre="";
			String MAIN="";
			String TBR="";
			String BBR_pre="";
			String SYR="";
			String PT="";  
			String sql1="select W.CUSTLISTNAME,t1.ps_trans_way,to_char(t1.trans_date,'yyyymmdd') as TRANSFER_DATE123,t1.trans_comment,t1.ps_issue_mode,t1.trans_address," +
					"t1.bank_owner,case when s.ifpeixun='1' then s.tl_dept_code else r.dept_code end as dept_code,s.loginname as loginname1,to_char(t1.createddate,'yyyymmdd') as TRSDATE,CNTR_PRESS_NO,APPL_NO_QA," +
					"to_char(t1.toubao_date,'yyyymmdd') as APPDATE,t1.third_company_organ,p1.pol_code,t1.simple_id,t1.ERNST_MONEYIN_TYPE,t1.BANK_CODE," +
					"t1.BANKACC_NO,t1.BANKACC_TYPE,t1.MONEYIN_TYPE,t1.trans_way,to_char(t1.trans_date,'yyyymmdd') as DELIVER_DATE,t1.trans_address,s1.loginname," +
					"to_char(t1.qa_date,'yyyymmdd') as INSPECT_TIME,t1.premium*t1.mon_num_period*100 as INITIAL_PREMIUM,t1.mon_num_period,t1.trans_address,t1.account_owner," +
					"t1.ivr_paid_status,to_char(t1.ivr_paid_date,'yyyymmdd') as ivr_paid_date,t1.IVR_REAL_ORDER_NO as ivr_order_no,t1.ivr_bank_code,t1.ivr_paid_amt," +
					"i1.name as name1,i1.gender as gender1," +
					"to_char(i1.birthday,'yyyymmdd') as BIRTH1,i1.idtype as idtype1,i1.id as id1,i1.address as address1,i1.zipcode as zipcode1,i1.tel as tel1," +
					"i1.mobile as mobile1,i1.email as email1,i1.b_relationship as b_relationship1," +
					"i2.name as name2," +
					"i2.gender as gender2,to_char(i2.birthday,'yyyymmdd') as BIRTH2,i2.idtype as idtype2,i2.id as id2,i2.address as address2," +
					"i2.zipcode as zipcode2,i2.tel as tel2,i2.mobile as mobile2,i2.email as email2 " +
					"from workorder2 w left join tabcinsurance t1 on w.workorder_guid=t1.relation_id left join staff s on s.staff_id=w.createdby " +
					"left join staffrolegroup sr on s.staff_id=sr.staff_id left join rolegroup r on r.rolegroup_id=sr.rolegroup_id " +
					"left join policy p1 on p1.pol_guid=t1.pol_package left join staff s1 on s1.staff_id=t1.QA_staff " +
					"left join (select cust_guid,relation_id,name,gender,birthday,idtype,upper(id) id,address,zipcode,tel,mobile,email,jobcode," +
					"b_relationship from insurance_cust where cust_type=1) i1 on i1.relation_id=t1.relation_id left join " +
					"(select cust_guid,relation_id,name,gender,birthday,idtype,upper(id) id,address,zipcode,tel,mobile,email," +
					"jobcode,b_relationship from insurance_cust where cust_type=2) i2 on i2.relation_id=t1.relation_id " +
					"where  t1.relation_id='"+realtionID+"'";
			log.debug("sql1:"+sql1);
			List list1=ISPayServlet.ebean.chaxun_sql(sql1,dataSource1);
			if(list1!=null&&list1.size()>0){
				Map map1=(Map)list1.get(0);
				APPL_NO_QA=Util.getString(map1.get("APPL_NO_QA"));
				DIST="<DIST><SEAT_DEPT>"+Util.getString(map1.get("dept_code"))+"</SEAT_DEPT>" +
						"<SEAT_CODE>"+Util.getString(map1.get("loginname1"))+"</SEAT_CODE>" +
						"<INSU>101</INSU><BATCH_NO>"+Util.getString(map1.get("CUSTLISTNAME"))+"</BATCH_NO></DIST>";
				log.debug("DIST:"+DIST);
				BUSI_pre="<TRSDATE>"+Util.getString(map1.get("TRSDATE"))+"</TRSDATE><TRANS>"+Util.getString(map1.get("CNTR_PRESS_NO"))+"</TRANS><CATE>2</CATE><SUBJECT>1</SUBJECT>";
				log.debug("BUSI_pre:"+BUSI_pre);
				MAIN="<MAIN><APPNO>"+Util.getString(map1.get("APPL_NO_QA"))+"</APPNO>" +
						"<APPDATE>"+Util.getString(map1.get("APPDATE"))+"</APPDATE>" +
						"<ORGAN>"+Util.getString(map1.get("third_company_organ"))+"</ORGAN>" +
						"<BLUE_CODE>"+Util.getString(map1.get("pol_code"))+"</BLUE_CODE>" +
						"<BALE_NO>"+Util.getString(map1.get("simple_id"))+"</BALE_NO>" +
						"<PAY_WAY>"+Util.getString(map1.get("ERNST_MONEYIN_TYPE"))+"</PAY_WAY>" +
						"<PAYBANK>"+Util.getString(map1.get("BANK_CODE"))+"</PAYBANK>" +
						"<PAYACC>"+Util.getString(map1.get("BANKACC_NO"))+"</PAYACC>" +
						"<ACCTYPE>"+Util.getString(map1.get("BANKACC_TYPE"))+"</ACCTYPE>" +
						"<PAY_T>"+Util.getString(map1.get("MONEYIN_TYPE"))+"</PAY_T>" +
//						"<PARTNER_CARDNO></PARTNER_CARDNO>" +
//						"<DELIVER>"+Util.getString(map1.get("trans_way"))+"</DELIVER>" +
						"<DELIVER></DELIVER>" +
						"<DELIVER_DATE>"+Util.getString(map1.get("DELIVER_DATE"))+"</DELIVER_DATE>" +
						"<DELIVER_MEMO>"+Util.getString(map1.get("trans_address"))+"</DELIVER_MEMO>" +
						"<SPEC></SPEC><PRINTED>0</PRINTED><FAMILY_TYPE>0</FAMILY_TYPE><FAMILY_APP_ID></FAMILY_APP_ID>" +
						"<INSPECT_EMP>"+Util.getString(map1.get("loginname"))+"</INSPECT_EMP>" +
						"<INSPECT_TIME>"+Util.getString(map1.get("INSPECT_TIME"))+"</INSPECT_TIME>" +
						"<INITIAL_PREMIUM>"+Util.getString(map1.get("INITIAL_PREMIUM"))+"</INITIAL_PREMIUM>" +
						"<MON_NUM_PERIOD>"+Util.getString(map1.get("mon_num_period"))+"</MON_NUM_PERIOD>" +
						"<AUTH_NO></AUTH_NO><AUTH_DATE></AUTH_DATE><KIDS_DEATH_AMOUNT></KIDS_DEATH_AMOUNT>" +
//						"<DELIVER_ADDR>"+Util.getString(map1.get("trans_address"))+"</DELIVER_ADDR>" +
//						"<ACCOUNT_OWNER>"+Util.getString(map1.get("bank_owner"))+"</ACCOUNT_OWNER>" +
//						"<PAID_STATUS>"+Util.getString(map1.get("ivr_paid_status"))+"</PAID_STATUS>" +
//						"<PAID_DATE>"+Util.getString(map1.get("ivr_paid_date"))+"</PAID_DATE>" +
//						"<BANK_CODE>"+Util.getString(map1.get("ivr_bank_code"))+"</BANK_CODE>" +
//						"<ORDER_NO>"+Util.getString(map1.get("ivr_order_no"))+"</ORDER_NO>" +
						"<TRANSFER>"+Util.getString(map1.get("ps_trans_way"))+"</TRANSFER>" +
						"<TRANSFER_DATE>"+Util.getString(map1.get("TRANSFER_DATE123"))+"</TRANSFER_DATE>" +
						"<TRANSFER_MEMO>"+Util.getString(map1.get("trans_comment"))+"</TRANSFER_MEMO>" +
						"<ISSUE_MODE>"+Util.getString(map1.get("ps_issue_mode"))+"</ISSUE_MODE>" +
						"<TRANSFER_ADDR>"+Util.getString(map1.get("trans_address"))+"</TRANSFER_ADDR>" + 
						"</MAIN>";
				log.debug("MAIN:"+MAIN);
				TBR="<TBR><NAME>"+Util.getString(map1.get("name1"))+"</NAME>" +
						"<SEX>"+Util.getString(map1.get("gender1"))+"</SEX>" +
						"<BIRTH>"+Util.getString(map1.get("BIRTH1"))+"</BIRTH>" +
						"<IDTYPE>"+Util.getString(map1.get("idtype1"))+"</IDTYPE>" +
						"<IDNO>"+Util.getString(map1.get("id1"))+"</IDNO>" +
						"<ADDR>"+Util.getString(map1.get("address1"))+"</ADDR>" +
						"<ZIP>"+Util.getString(map1.get("zipcode1"))+"</ZIP>" +
						"<TEL>"+Util.getString(map1.get("tel1"))+"</TEL>" +
//						"<TEL_OFFICE></TEL_OFFICE>" +
						"<MP>"+Util.getString(map1.get("mobile1"))+"</MP>" +
						"<EMAIL>"+Util.getString(map1.get("email1"))+"</EMAIL>" +
						"<OCCUP></OCCUP><BBR_RELA>"+Util.getString(map1.get("b_relationship1"))+"</BBR_RELA></TBR>";
				log.debug("TBR:"+TBR);
				BBR_pre="<NAME>"+Util.getString(map1.get("name2"))+"</NAME>" +
				        "<SEX>"+Util.getString(map1.get("gender2"))+"</SEX>" +
				        "<BIRTH>"+Util.getString(map1.get("BIRTH2"))+"</BIRTH>" +
				        "<IDTYPE>"+Util.getString(map1.get("idtype2"))+"</IDTYPE>" +
				        "<IDNO>"+Util.getString(map1.get("id2"))+"</IDNO>" +
				        "<ADDR>"+Util.getString(map1.get("address2"))+"</ADDR>" +
				        "<ZIP>"+Util.getString(map1.get("zipcode2"))+"</ZIP>" +
				        "<TEL>"+Util.getString(map1.get("tel2"))+"</TEL>" +
//				        "<TEL_OFFICE></TEL_OFFICE>" +
				        "<MP>"+Util.getString(map1.get("mobile2"))+"</MP>" +
				        "<EMAIL>"+Util.getString(map1.get("email2"))+"</EMAIL>" +
						"<OCCUP></OCCUP>";
				log.debug("BBR_pre:"+BBR_pre);
			}
			String sql2="select name,gender,to_char(birthday,'yyyymmdd') as BIRTH,idtype,upper(id) as IDNO," +
					"b_index,INTERESTPERCENT,b_relationship from INSURANCE_cust where RELATION_ID='"+realtionID+"' and cust_type=3";
			log.debug("sql2:"+sql2);
			List list2=ISPayServlet.ebean.chaxun_sql(sql2,dataSource1);
			if(list2!=null&&list2.size()>0){
				for(int i=0;i<list2.size();i++){
					Map map2=(Map)list2.get(i);
					SYR=SYR+"<SYR><NAME>"+Util.getString(map2.get("name"))+"</NAME>" +
							"<SEX>"+Util.getString(map2.get("gender"))+"</SEX>" +
							"<BIRTH>"+Util.getString(map2.get("BIRTH"))+"</BIRTH>" +
							"<IDTYPE>"+Util.getString(map2.get("idtype"))+"</IDTYPE>" +
							"<IDNO>"+Util.getString(map2.get("IDNO"))+"</IDNO>" +
							"<ORDER>"+Util.getString(map2.get("b_index"))+"</ORDER>" +
							"<RATIO>"+Util.getString(map2.get("INTERESTPERCENT"))+"</RATIO>" +
							"<BBR_RELA>"+Util.getString(map2.get("b_relationship"))+"</BBR_RELA></SYR>";
				}
			}
			log.debug("SYR:"+SYR);
			String sql3="select i.pol_code,i.face_amnt,i.chargeperiod,i.MONEYIN_DUR,i.coverageperiod," +
					"i.INSUR_DUR,'','','','',i.premium*100 as PREMIUM,i.premium*t.mon_num_period*100 as INITIAL_PREMIUMOFPT," +
					"'','','',1.00 from insurance i left join tabcinsurance t on t.relation_id=i.relation_id " +
					"left join policy_package p on p.pol_guid=t.pol_package and p.simple_id=to_char(t.simple_id) " +
					"and p.item_guid=i.pol_guid where i.relation_id='"+realtionID+"' order by p.plan_seq";
			log.debug("sql3:"+sql3);
			List list3=ISPayServlet.ebean.chaxun_sql(sql3,dataSource1);
			if(list3!=null&&list3.size()>0){
				for(int i=0;i<list3.size();i++){
					Map map3=(Map)list3.get(i);
					PT=PT+"<PT><ID>"+Util.getString(map3.get("pol_code"))+"</ID>" +
							"<UNIT>"+Util.getString(map3.get("face_amnt"))+"</UNIT>" +
							"<CRG_T>"+Util.getString(map3.get("chargeperiod"))+"</CRG_T>" +
							"<CRG_Y>"+Util.getString(map3.get("MONEYIN_DUR"))+"</CRG_Y>" +
							"<COVER_T>"+Util.getString(map3.get("coverageperiod"))+"</COVER_T>" +
							"<COVER_Y>"+Util.getString(map3.get("INSUR_DUR"))+"</COVER_Y>" +
							"<DRAW_T></DRAW_T><DRAW_FST></DRAW_FST><DRAW_LST></DRAW_LST><DRAW_ENSURE></DRAW_ENSURE>" +
							"<PREMIUM>"+Util.getString(map3.get("PREMIUM"))+"</PREMIUM>" +
							"<INITIAL_PREMIUMOFPT>"+Util.getString(map3.get("INITIAL_PREMIUMOFPT"))+"</INITIAL_PREMIUMOFPT>" +
							"<PR_TYPE></PR_TYPE><FREE_TYPE></FREE_TYPE><FREE_MONTH></FREE_MONTH><DISCOUNT_RATE>1.00</DISCOUNT_RATE></PT>";
				}
			}
			log.debug("PT:"+PT);
			TxXml="<TX><REQUEST>"+DIST+"<BUSI>"+BUSI_pre+"<CONTENT>"+MAIN+TBR+"<BBR>"+BBR_pre+SYR+"</BBR><PTS>"+PT+"</PTS></CONTENT></BUSI></REQUEST></TX>";
			String returnresult=ISPayServlet.ebean.sp_appl_tb_updatetabc(realtionID,newguid);
			log.debug("returnresult:"+returnresult);
		}catch(Exception e){
			log.error("getTxXml(String realtionID):"+Util.getERRO(e));
		}
		log.debug("TxXml:"+TxXml);
		tongbu_num1=tongbu_num1+1;
		return TxXml;
	}
	private void dorun2(DataSource dataSource1) throws Exception{
		String sql="select t.relation_id as workorder_guid from workorder2 w left join tabcinsurance t on w.workorder_guid=t.relation_id inner join staff s on s.staff_id=w.createdby where w.workorderstatus='OPEN' and curstep_id ='N00032' and appl_tb_list is  null and (ivr_flag=0 or ivr_flag is null)";
	    List list=ISPayServlet.ebean.chaxun_sql(sql, dataSource1);
	    if(list!=null&&list.size()>0){
	    	for(int i=0;i<list.size();i++){
	    		tongbu_num=tongbu_num-1;
	    		if(tongbu_num>0){
		    		Map map=(Map)list.get(i);
					String workorder_guid=(String)map.get("workorder_guid");
					String ResultXml=getTxXml(workorder_guid,dataSource1);
					xml=xml+ResultXml;
					log.debug("xml:"+xml);
	    		}else{
	    			break;
	    		}
	    	}
	    }
	}
	private void dorun1(DataSource dataSource1) throws Exception{
		String sql="select CHECK_APPLTD() FROM DUAL";
		String dorun_judge=ISPayServlet.ebean.chaxun_string(sql, dataSource1);
		if(dorun_judge.equals("YES")&&tongbu_num>0){
			dorun2(dataSource1);
		}
	}
	private void dorun() throws Exception{
		String sql="select mproject_id from multiproject where mproject_id!='gzl111' ";
		log.debug("sql:"+sql);
		List list=ISPayServlet.ebean.chaxun_sql1(sql);
		if(list!=null&&list.size()>0){
			tongbu_num1=0;
			tongbu_num=num;
		    newguid=Util.ReturnCode1();
		    log.debug("newguid:"+newguid);
		    String result=ISPayServlet.ebean.sp_appl_tb_insertlist(newguid);
		    log.debug("result:"+result);
		    if(result.equals("1")){
		    	xml="";
				for(int i=0;i<list.size();i++){
					Map map=(Map)list.get(i);
					String mproject_id=(String)map.get("mproject_id");
					DataSource dataSource1=(DataSource)ISPayServlet.wac.getBean(mproject_id);
					try {
						if(tongbu_num>0){
							dorun1(dataSource1);
						}
					} catch (Exception e) {
						log.error("dorun():"+Util.getERRO(e));
					}
				}
				if(xml==null||xml.length()==0||xml.equals("")){
					String result3=ISPayServlet.ebean.sp_appl_tb_query_return(newguid,3,"该批次保单为空");
					log.debug("result3:"+result3);
					return;
				}
				xml="<?xml version='1.0' encoding='GBK'?><TXS><LIST>"+newguid+"</LIST><NUM>"+tongbu_num1+"</NUM>"+xml+"</TXS>";
				log.debug("xml:"+xml);
				log.debug("url:"+url);
				String List="";
				String ERR_CODE="";
				try{
					String returnxml=ISPayServlet.ISPayConnection1(url,"","",xml,"protocol","01","packet");
					log.debug("returnxml:"+returnxml);
					Document doc=DocumentHelper.parseText(returnxml); 
					Element root=doc.getRootElement(); 
					Element LIST_eml=root.element("LIST");
					Element ERR_CODE_eml=root.element("ERR_CODE");
					Element ERR_DESC_eml=root.element("ERR_DESC");
					List=LIST_eml.getText();
					log.debug("List:"+List);
					ERR_CODE=ERR_CODE_eml.getText();
					log.debug("ERR_CODE:"+ERR_CODE);
					log.debug("ERR_CODE.length():"+ERR_CODE.length());
					ERR_CODE=ERR_CODE.replace(" ","");
					log.debug("ERR_CODE_new:"+ERR_CODE);
					log.debug("ERR_CODE_new.length():"+ERR_CODE.length());
					String ERR_DESC=ERR_DESC_eml.getText();
					log.debug("ERR_DESC:"+ERR_DESC);
				}catch(Exception e){
					String result2=ISPayServlet.ebean.sp_appl_tb_return(newguid,0);
					log.debug("result2:"+result2);
					log.error(Util.getERRO(e));
					return;
				}
				String result1=ISPayServlet.ebean.sp_appl_tb_return(List,Integer.parseInt(ERR_CODE));
				log.debug("result1:"+result1);
		    }
		} 
	}
	public void run(){
		while(flag){
			try{
				dorun();
			}catch(Exception e){
				log.error("run():"+Util.getERRO(e));
			}
			try{
            	Thread.sleep(HZ*1000);
            }catch(Exception e){
            	log.error("定时错误:"+Util.getERRO(e)); 
            }
		}
	}
	

}
